<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
    
  
  <link href="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Web,JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="表单脚本富文本编辑富文本编辑，又称为WYSIWYG（What You See Is What You Get，所见即所得）。在网页中编辑富文本内容，是人们对Web 应用程序最大的期待之一。这一技术的本质，就是在页面中嵌入一个包含空HTML 页面的iframe。通过设置designMode 属性，这个空白的HTML 页面可以被编辑，而编辑对象则是该页面&amp;lt;body&amp;gt;元素的HTML 代码。d">
<meta property="og:type" content="article">
<meta property="og:title" content="《 JavaScript 高级程序设计》备忘-第十四章-4">
<meta property="og:url" content="http://codingme.xyz/2016/10/20/javascript-note-14-4/index.html">
<meta property="og:site_name" content="CodingMe">
<meta property="og:description" content="表单脚本富文本编辑富文本编辑，又称为WYSIWYG（What You See Is What You Get，所见即所得）。在网页中编辑富文本内容，是人们对Web 应用程序最大的期待之一。这一技术的本质，就是在页面中嵌入一个包含空HTML 页面的iframe。通过设置designMode 属性，这个空白的HTML 页面可以被编辑，而编辑对象则是该页面&amp;lt;body&amp;gt;元素的HTML 代码。d">
<meta property="og:updated_time" content="2016-11-03T08:21:28.649Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《 JavaScript 高级程序设计》备忘-第十四章-4">
<meta name="twitter:description" content="表单脚本富文本编辑富文本编辑，又称为WYSIWYG（What You See Is What You Get，所见即所得）。在网页中编辑富文本内容，是人们对Web 应用程序最大的期待之一。这一技术的本质，就是在页面中嵌入一个包含空HTML 页面的iframe。通过设置designMode 属性，这个空白的HTML 页面可以被编辑，而编辑对象则是该页面&amp;lt;body&amp;gt;元素的HTML 代码。d">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codingme.xyz/2016/10/20/javascript-note-14-4/"/>





  <title> 《 JavaScript 高级程序设计》备忘-第十四章-4 | CodingMe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">CodingMe</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://codingme.xyz/2016/10/20/javascript-note-14-4/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Huang SJ">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="CodingMe">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="CodingMe" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                《 JavaScript 高级程序设计》备忘-第十四章-4
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="表单脚本"><a href="#表单脚本" class="headerlink" title="表单脚本"></a>表单脚本</h1><h2 id="富文本编辑"><a href="#富文本编辑" class="headerlink" title="富文本编辑"></a>富文本编辑</h2><p>富文本编辑，又称为WYSIWYG（What You See Is What You Get，所见即所得）。<br>在网页中编辑富文本内容，是人们对Web 应用程序最大的期待之一。<br>这一技术的本质，就是在页面中嵌入一个包含空HTML 页面的iframe。<br>通过设置designMode 属性，这个空白的HTML 页面可以被编辑，<br>而编辑对象则是该页面<code>&lt;body&gt;</code>元素的HTML 代码。<br>designMode 属性有两个可能的值：”off”（默认值）和”on”。<br>在设置为”on”时，整个文档都会变得可以编辑（显示插入符号），然后就可以像使用字处理软件一样，通过键盘将文本内容加粗、变成斜体。</p>
<p>可以给iframe 指定一个非常简单的HTML 页面作为其内容来源。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>Blank Page for Rich Text Editing<span class="tag">&lt;/<span class="name">title</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></div></pre></td></tr></table></figure>
<a id="more"></a>
<p>这个页面在iframe 中可以像其他页面一样被加载。<br>要让它可以编辑，必须要将designMode 设置为”on”，但只有在页面完全加载之后才能设置这个属性。<br>因此，在包含页面中，需要使用onload 事件处理程序来在恰当的时刻设置designMode。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">iframe</span> <span class="attr">name</span>=<span class="string">"richedit"</span> <span class="attr">style</span>=<span class="string">"height:100px;width:100px;"</span> <span class="attr">src</span>=<span class="string">"blank.htm"</span>&gt;</span><span class="tag">&lt;/<span class="name">iframe</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="javascript"></span></div><div class="line">EventUtil.addHandler(<span class="built_in">window</span>, <span class="string">"load"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    frames[<span class="string">"richedit"</span>].document.designMode = <span class="string">"on"</span>;</div><div class="line">&#125;);</div><div class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div></pre></td></tr></table></figure>
<p>以上代码执行之后，就会在页面中看到一个类似文本框的可编辑区字段。<br>这个区字段具有与其他网页相同的默认样式；不过，通过为空白页面应用CSS 样式，可以修改可编辑区字段的外观。</p>
<h3 id="使用contenteditable属性"><a href="#使用contenteditable属性" class="headerlink" title="使用contenteditable属性"></a>使用contenteditable属性</h3><p>另一种编辑富文本内容的方式是使用名为 contenteditable 的特殊属性，这个属性也是由IE 最早实现的。<br>可以把contenteditable 属性应用给页面中的任何元素，然后用户立即就可以编辑该元素。<br>这种方法之所以受到欢迎，是因为它不需要iframe、空白页和JavaScript，只要为元素设置contenteditable 属性即可。<br>元素中包含的任何文本内容就都可以编辑了，就好像这个元素变成了<code>&lt;textarea&gt;</code>元素一样。<br>contenteditable 属性有三个可能的值：”true”表示打开、”false”表示关闭，”inherit”表示从父元素那里继承。</p>
<p>支持contenteditable属性的元素有IE、Firefox、Chrome、Safari 和Opera。</p>
<h3 id="操作富文本"><a href="#操作富文本" class="headerlink" title="操作富文本"></a>操作富文本</h3><p>与富文本编辑器交互的主要方式，就是使用document.execCommand()。<br>这个方法可以对文档执行预定义的命令，而且可以应用大多数格式。<br>可以为document.execCommand()方法传递3 个参数：<br>要执行的命令名称、表示浏览器是否应该为当前命令提供用户界面的一个布尔值<br>和执行命令必须的一个值（如果不需要值，则传递null）。</p>
<p>为了确保跨浏览器的兼容性，第二个参数应该始终设置为false，因为Firefox 会在该参数为true 时抛出错误。</p>
<p>与剪贴板有关的命令在不同浏览器中的差异极大。</p>
<p>可以在任何时候使用这些命令来修改富文本区域的外观。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//转换粗体文本</span></div><div class="line">frames[<span class="string">"richedit"</span>].document.execCommand(<span class="string">"bold"</span>, <span class="literal">false</span>, <span class="literal">null</span>);</div><div class="line"><span class="comment">//转换斜体文本</span></div><div class="line">frames[<span class="string">"richedit"</span>].document.execCommand(<span class="string">"italic"</span>, <span class="literal">false</span>, <span class="literal">null</span>);</div><div class="line"><span class="comment">//创建指向www.wrox.com 的链接</span></div><div class="line">frames[<span class="string">"richedit"</span>].document.execCommand(<span class="string">"createlink"</span>, <span class="literal">false</span>,</div><div class="line"><span class="string">"http://www.wrox.com"</span>);</div><div class="line"><span class="comment">//格式化为1 级标题</span></div><div class="line">frames[<span class="string">"richedit"</span>].document.execCommand(<span class="string">"formatblock"</span>, <span class="literal">false</span>, <span class="string">"&lt;h1&gt;"</span>);</div></pre></td></tr></table></figure>
<p>同样的方法也适用于页面中contenteditable 属性为”true”的区块，只要把对框架的引用替换成当前窗口的document 对象即可。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//转换粗体文本</span></div><div class="line"><span class="built_in">document</span>.execCommand(<span class="string">"bold"</span>, <span class="literal">false</span>, <span class="literal">null</span>);</div><div class="line"><span class="comment">//转换斜体文本</span></div><div class="line"><span class="built_in">document</span>.execCommand(<span class="string">"italic"</span>, <span class="literal">false</span>, <span class="literal">null</span>);</div><div class="line"><span class="comment">//创建指向www.wrox.com 的链接</span></div><div class="line"><span class="built_in">document</span>.execCommand(<span class="string">"createlink"</span>, <span class="literal">false</span>,</div><div class="line"><span class="string">"http://www.wrox.com"</span>);</div><div class="line"><span class="comment">//格式化为1 级标题</span></div><div class="line"><span class="built_in">document</span>.execCommand(<span class="string">"formatblock"</span>, <span class="literal">false</span>, <span class="string">"&lt;h1&gt;"</span>);</div></pre></td></tr></table></figure>
<p>虽然所有浏览器都支持这些命令，但这些命令所产生的HTML 仍然有很大不同。<br>例如，执行bold 命令时，IE 和Opera 会使用<code>&lt;strong&gt;</code>标签包围文本，Safari 和Chrome 使用<code>&lt;b&gt;</code>标签，而Firefox 则使用<code>&lt;span&gt;</code>标签。<br>由于各个浏览器实现命令的方式不同，加上它们通过innerHTML 实现转换的方式也不一样，因此不能指望富文本编辑器会产生一致的HTML。</p>
<p>除了命令之外，还有一些与命令相关的方法。<br>第一个方法就是queryCommandEnabled()，可以用它来检测是否可以针对当前选择的文本，或者当前插入字符所在位置执行某个命令。<br>接收一个参数，即要检测的命令。如果当前编辑区域允许执行传入的命令，这个方法返回true，否则返回false。<br><code>var result = frames[&quot;richedit&quot;].document.queryCommandEnabled(&quot;bold&quot;);</code><br>如果能够对当前选择的文本执行”bold”命令，以上代码会返回true。<br>需要注意的是，queryCommandEnabled()方法返回true，并不意味着实际上就可以执行相应命令，而只能说明对当前选择的文本执行相应命令是否合适。<br>例如，Firefox 在默认情况下会禁用剪切操作，但执行queryCommandEnabled(“cut”)也可能会返回true。</p>
<p>queryCommandState()方法用于确定是否已将指定命令应用到了选择的文本。<br>例如，要确定当前选择的文本是否已经转换成了粗体:<br><code>var isBold = frames[&quot;richedit&quot;].document.queryCommandState(&quot;bold&quot;);</code><br>如果此前已经对选择的文本执行了”bold”命令，那么上面的代码会返回true。<br>一些功能全面的富文本编辑器，正是利用这个方法来更新粗体、斜体等按钮的状态的。<br>最后一个方法是queryCommandValue()，用于取得执行命令时传入的值（即前面例子中传给document.execCommand()的第三个参数）。<br>例如，在对一段文本应用”fontsize”命令时如果传入了7，那么下面的代码就会返回”7”：<br><code>var fontSize = frames[&quot;richedit&quot;].document.queryCommandValue(&quot;fontsize&quot;);</code></p>
<h3 id="富文本选区"><a href="#富文本选区" class="headerlink" title="富文本选区"></a>富文本选区</h3><p>在富文本编辑器中，使用框架（iframe）的getSelection()方法，可以确定实际选择的文本。<br>这个方法是window 对象和document 对象的属性，调用它会返回一个表示当前选择文本的Selection对象。<br>每个Selection 对象都有下列属性。</p>
<ul>
<li>anchorNode：选区起点所在的节点。</li>
<li>anchorOffset：在到达选区起点位置之前跳过的anchorNode 中的字符数量。</li>
<li>focusNode：选区终点所在的节点。</li>
<li>focusOffset：focusNode 中包含在选区之内的字符数量。</li>
<li>isCollapsed：布尔值，表示选区的起点和终点是否重合。</li>
<li>rangeCount：选区中包含的DOM 范围的数量。</li>
</ul>
<p>Selection 对象的这些属性并没有包含多少有用的信息。<br>好在，该对象的方法提供了更多信息，并且支持对选区的操作。</p>
<ul>
<li>addRange(range)：将指定的DOM 范围添加到选区中。</li>
<li>collapse(node, offset)：将选区折叠到指定节点中的相应的文本偏移位置。</li>
<li>collapseToEnd()：将选区折叠到终点位置。</li>
<li>collapseToStart()：将选区折叠到起点位置。</li>
<li>containsNode(node)：确定指定的节点是否包含在选区中。</li>
<li>deleteFromDocument()：从文档中删除选区中的文本，与document.execCommand(“delete”,false, null)命令的结果相同。</li>
<li>extend(node, offset)：通过将focusNode 和focusOffset 移动到指定的值来扩展选区。</li>
<li>getRangeAt(index)：返回索引对应的选区中的DOM范围。</li>
<li>removeAllRanges()：从选区中移除所有DOM 范围。实际上，这样会移除选区，因为选区中至少要有一个范围。</li>
<li>reomveRange(range)：从选区中移除指定的DOM 范围。</li>
<li>selectAllChildren(node)：清除选区并选择指定节点的所有子节点。</li>
<li>toString()：返回选区所包含的文本内容。</li>
</ul>
<p>利用了DOM范围来管理选区。<br>由于可以直接操作选择文本的DOM 表现，因此访问DOM范围与使用execCommand()相比，能够对富文本编辑器进行更加细化的控制。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> selection = frames[<span class="string">"richedit"</span>].getSelection();</div><div class="line"><span class="comment">//取得选择的文本</span></div><div class="line"><span class="keyword">var</span> selectedText = selection.toString();</div><div class="line"><span class="comment">//取得代表选区的范围</span></div><div class="line"><span class="keyword">var</span> range = selection.getRangeAt(<span class="number">0</span>);</div><div class="line"><span class="comment">//突出显示选择的文本</span></div><div class="line"><span class="keyword">var</span> span = frames[<span class="string">"richedit"</span>].document.createElement(<span class="string">"span"</span>);</div><div class="line">span.style.backgroundColor = <span class="string">"yellow"</span>;</div><div class="line">range.surroundContents(span);</div></pre></td></tr></table></figure>
<p>以上代码会为富文本编辑器中被选择的文本添加黄色的背景。<br>这里使用了默认选区中的DOM 范围，通过surroundContents()方法将选区添加到了带有黄色背景的<code>&lt;span&gt;</code>元素中。</p>
<p>HTML5 将getSelection()方法纳入了标准，而且IE9、Firefox、Safari、Chrome 和Opera 8 都实现了它。</p>
<p>IE8 及更早的版本不支持DOM范围，但我们可以通过它支持的selection 对象操作选择的文本。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> range = frames[<span class="string">"richedit"</span>].document.selection.createRange();</div><div class="line"><span class="keyword">var</span> selectedText = range.text;</div></pre></td></tr></table></figure>
<p>虽然使用IE 的文本范围来执行HTML 操作并不像使用DOM 范围那么可靠，但也不失为一种有效的途径。<br>要像前面使用DOM 范围那样实现相同的文本高亮效果，可以组合使用htmlText 属性和pasteHTML()方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> range = frames[<span class="string">"richedit"</span>].document.selection.createRange();</div><div class="line">range.pasteHTML(<span class="string">"&lt;span style=\"background-color:yellow\"&gt; "</span> + range.htmlText +<span class="string">"&lt;/span&gt;"</span>);</div></pre></td></tr></table></figure>
<h3 id="表单与富文本"><a href="#表单与富文本" class="headerlink" title="表单与富文本"></a>表单与富文本</h3><p>由于富文本编辑是使用iframe 而非表单控件实现的，因此从技术上说，富文本编辑器并不属于表单。<br>换句话说，富文本编辑器中的HTML 不会被自动提交给服务器，而需要我们手工来提取并提交HTML。<br>为此，通常可以添加一个隐藏的表单字段，让它的值等于从iframe 中提取出的HTML。<br>就是在提交表单之前，从iframe 中提取出HTML，并将其插入到隐藏的字段中。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">EventUtil.addHandler(form, <span class="string">"submit"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="keyword">var</span> target = EventUtil.getTarget(event);</div><div class="line">    target.elements[<span class="string">"comments"</span>].value = frames[<span class="string">"richedit"</span>].document.body.innerHTML;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>在此，我们通过文档主体的innerHTML 属性取得了iframe 中的HTML，然后将其插入到了名为”comments”的表单字段中。<br>这样可以确保恰好在提交表单之前填充”comments”字段。</p>
<p>对于contenteditable元素，也可以执行类似操作。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">EventUtil.addHandler(form, <span class="string">"submit"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="keyword">var</span> target = EventUtil.getTarget(event);</div><div class="line">    target.elements[<span class="string">"comments"</span>].value =</div><div class="line">    <span class="built_in">document</span>.getElementById(<span class="string">"richedit"</span>).innerHTML;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Web/" rel="tag"># Web</a>
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/19/javascript-note-14-3/" rel="next" title="《 JavaScript 高级程序设计》备忘-第十四章-3">
                <i class="fa fa-chevron-left"></i> 《 JavaScript 高级程序设计》备忘-第十四章-3
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/23/javascript-note-15-1/" rel="prev" title="《 JavaScript 高级程序设计》备忘-第十十五章-1">
                《 JavaScript 高级程序设计》备忘-第十十五章-1 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="Huang SJ" />
          <p class="site-author-name" itemprop="name">Huang SJ</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">75</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hsj1992" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/hsj9527" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1694147905" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.freecodecamp.cn/hsj1992" target="_blank" title="FreeCodeCamp">
                  
                    <i class="fa fa-fw fa-fire"></i>
                  
                  FreeCodeCamp
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://codepen.io/hsj1992/" target="_blank" title="codepen">
                  
                    <i class="fa fa-fw fa-codepen"></i>
                  
                  codepen
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://hsj1992.oschina.io/" target="_blank" title="码云镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  码云镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.coding.me/" target="_blank" title="coding镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  coding镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.github.io/" target="_blank" title="github镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  github镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://codingme-6dd8a.firebaseapp.com" target="_blank" title="Firebase镜像">
                  
                    <i class="fa fa-fw fa-google"></i>
                  
                  Firebase镜像
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#表单脚本"><span class="nav-number">1.</span> <span class="nav-text">表单脚本</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#富文本编辑"><span class="nav-number">1.1.</span> <span class="nav-text">富文本编辑</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用contenteditable属性"><span class="nav-number">1.1.1.</span> <span class="nav-text">使用contenteditable属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#操作富文本"><span class="nav-number">1.1.2.</span> <span class="nav-text">操作富文本</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#富文本选区"><span class="nav-number">1.1.3.</span> <span class="nav-text">富文本选区</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#表单与富文本"><span class="nav-number">1.1.4.</span> <span class="nav-text">表单与富文本</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Huang SJ</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
